package cn.ptu.pmaa.service;

import cn.ptu.pmaa.entities.RespBean;
import cn.ptu.pmaa.mapper.LoginRegMapper;
import cn.ptu.pmaa.utils.DateUtil;
import cn.ptu.pmaa.utils.EmailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;

@Service
public class LoginRegService {

    @Autowired
    DateUtil dateUtil;
    @Autowired
    EmailUtil emailUtil;
    @Autowired(required = false)
    LoginRegMapper loginRegMapper;
    @Autowired(required = false)
    HttpServletRequest httpServletRequest;

    public int login(String id,String pwd,String role){
        if (role.equals("admin")){
            return loginRegMapper.adminlogin(id,pwd);
        }else if(role.equals("teacher")){
            return loginRegMapper.teacherlogin(id,pwd);
        }else{
            return loginRegMapper.studentlogin(id, pwd);
        }

    }

    public int register(String id,String pwd){
        return 0;
    }

    public int checkYzm(String id,String role,String pwd){
        if (role.equals("admin")){
            return loginRegMapper.adminEditPass(id,pwd);
        }else if(role.equals("teacher")){
            return loginRegMapper.teacherEditPass(id,pwd);
        }else{
            return loginRegMapper.studentEditPass(id, pwd);
        }
    }

    public int updatePwd( String id, String role){
        String email;int yzm;
        //获取邮箱
        if (role.equals("teacher")){
            email = loginRegMapper.getEmailFromTeacher(id);
        }else{
            email =  loginRegMapper.getEmailFromStudent(id);
        }
        if(email==null){
            return 0;
        }else {
            yzm=(int)((Math.random()*9+1)*1000);
            //发送验证码
            emailUtil.sendSimpleMail(email,""+yzm);
            httpServletRequest.getSession().setAttribute("yzm",""+yzm);
            //设置验证码发送时间
            httpServletRequest.getSession().setAttribute("sendtime",dateUtil.myDateTimeToString(new Date()));

        }
        HashMap<String,Object> data = new HashMap<>();
        data.put("yzm",yzm);
        return 1;
    }



}
